package com.common.service;

import io.github.thundzeng.miniemail.config.MailConfig;
import io.github.thundzeng.miniemail.constant.SmtpEnum;
import io.github.thundzeng.miniemail.core.MiniEmail;
import io.github.thundzeng.miniemail.core.MiniEmailFactory;
import io.github.thundzeng.miniemail.core.MiniEmailFactoryBuilder;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.servlet.http.HttpSession;
import java.util.Random;
import java.util.UUID;

/**
 * @author Tsing
 * 邮箱服务
 */


@Service
@Slf4j
public  class EmailService {

    @Value("${school-mail.username}")
    private  String username;
    @Value("${school-mail.password}")
    private String password;

    /**
     * 随机生成6位数的验证码
     * @return String code
     */
    private static String randomCode(){
        StringBuilder str = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            str.append(random.nextInt(10));
        }
        return str.toString();
    }

    /**
     * 给前端输入的邮箱，发送验证码 普通形式发送
     * 返回一个UUID存储到reids中 设置过期时间为一分钟
     * @param email
     * @return
     */

    //TODO 验证码过期待做
    public  String sendMimeMail( String email)  {
       MiniEmailFactory  miniEmailFactory =
                new MiniEmailFactoryBuilder().build(MailConfig.config(username, password)
                        .setMailDebug(false)
                        .setSenderNickname("校园趣坛")
                        .setMailSmtpHost(SmtpEnum.SMTP_QQ))
        ;
        MiniEmail miniEmail = miniEmailFactory.init();
        String code = randomCode();
        try {
            miniEmail.addCarbonCopy(new String[]{email}).send(email,"您的验证码为  "+code+"有效时间为一分钟");
            return UUID.randomUUID().toString();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return null;

    }


}
